package com.ruoyi.project.purchase.service.impl;

import java.util.List;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.domain.ResultBean;
import com.ruoyi.project.information.domain.TbCustomers;
import com.ruoyi.project.information.mapper.TbCustomersMapper;
import com.ruoyi.project.inventory.domain.RyInventory;
import com.ruoyi.project.inventory.mapper.RyInventoryMapper;
import com.ruoyi.project.purchase.domain.RyDepotDetail;
import com.ruoyi.project.purchase.domain.RyPurchaseOrder;
import com.ruoyi.project.purchase.domain.pojo.DepotDetailBean;
import com.ruoyi.project.purchase.domain.pojo.DepotHeadItem;
import com.ruoyi.project.purchase.domain.pojo.ParamBean;
import com.ruoyi.project.purchase.mapper.RyDepotDetailMapper;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.warehouse.domain.RyDepot;
import com.ruoyi.project.warehouse.domain.RyDepotItem;
import com.ruoyi.project.warehouse.domain.RyInventoryCurrentStock;
import com.ruoyi.project.warehouse.domain.WareCurrentStock;
import com.ruoyi.project.warehouse.mapper.RyDepotItemMapper;
import com.ruoyi.project.warehouse.mapper.RyDepotMapper;
import com.ruoyi.project.warehouse.mapper.WareCurrentStockMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.purchase.mapper.RyDepotHeadMapper;
import com.ruoyi.project.purchase.domain.RyDepotHead;
import com.ruoyi.project.purchase.service.IRyDepotHeadService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 单据主表Service业务层处理
 *
 * @author you
 * @date 2022-09-22
 */
@Service
public class RyDepotHeadServiceImpl implements IRyDepotHeadService
{
    @Autowired
    private RyDepotHeadMapper ryDepotHeadMapper;

    @Autowired
    private RyDepotDetailMapper ryDepotDetailMapper;

    @Autowired
    private RyDepotMapper ryDepotMapper;

    @Autowired
    private RyDepotItemMapper ryDepotItemMapper;

    @Autowired
    private TbCustomersMapper tbCustomersMapper;

    @Autowired
    private WareCurrentStockMapper wareCurrentStockMapper;

    @Autowired
    private RyInventoryMapper ryInventoryMapper;




    /**
     * 查询单据主表
     *
     * @param id 单据主表主键
     * @return 单据主表
     */
    @Override
    public RyDepotHead selectRyDepotHeadById(Long id)
    {
        return ryDepotHeadMapper.selectRyDepotHeadById(id);
    }

    /**
     * 查询单据主表及子表信息
     *
     * @param id 单据主表主键
     * @return 单据主表及子表信息
     */
    @Override
    public DepotHeadItem selectRyDepotDetailByDepotId(Long id)
    {

        DepotHeadItem depotHeadItem = new DepotHeadItem();
        RyDepotHead ryDepotHead = ryDepotHeadMapper.selectRyDepotHeadById(id);
        //主表数据
        depotHeadItem.setId(ryDepotHead.getId());
        depotHeadItem.setProjectCode(ryDepotHead.getProjectCode());
        depotHeadItem.setProjectName(ryDepotHead.getProjectName());
        depotHeadItem.setDepotId(ryDepotHead.getDepotId());
        depotHeadItem.setProjectStatus(ryDepotHead.getProjectStatus());
        depotHeadItem.setNumber(ryDepotHead.getNumber());
        depotHeadItem.setContractNumber(ryDepotHead.getContractNumber());
        depotHeadItem.setCreator(ryDepotHead.getCreator());
        depotHeadItem.setOperTime(ryDepotHead.getOperTime());
        depotHeadItem.setFileName(ryDepotHead.getFileName());
        depotHeadItem.setSalesMan(ryDepotHead.getSalesMan());
        depotHeadItem.setCreateTime(ryDepotHead.getCreateTime());
        depotHeadItem.setRemark(ryDepotHead.getRemark());
        //子表数据
        List<RyDepotItem> tableData = ryDepotItemMapper.selectRyDepotItemByDepotId(id);
        depotHeadItem.setTableData(tableData);
        return depotHeadItem;
    }

    /**
     * 新增单据主表及单据子表信息
     */
    @Override
    @Transactional
    public AjaxResult addDepotHeadAndDetail(DepotHeadItem depotHeadItem){
//获取用户信息
        SysUser user = SecurityUtils.getLoginUser().getUser();

        //判断是否有子表数据
        List<RyDepotItem> tableData = depotHeadItem.getTableData();
        if(tableData == null || tableData.size() ==0){
            return AjaxResult.error("子表数据不存在");
        }

        //新增项目库(每一个新建项目都会对应生成一个项目库)
        RyDepot ryDepot = new RyDepot();
        ryDepot.setName(depotHeadItem.getProjectName());
        ryDepot.setType("2");//2代表项目库
        ryDepot.setSort("3");//排序默认3,1和2代表总库和工具库
        int res1 =  ryDepotMapper.insertRyDepot(ryDepot);
        if(res1 > 0){//新增项目库成功
            //新增主表数据
            RyDepotHead ryDepotHead = new RyDepotHead();
            ryDepotHead.setDepotId(ryDepot.getId());
            ryDepotHead.setProjectCode(depotHeadItem.getProjectCode());
            ryDepotHead.setProjectName(depotHeadItem.getProjectName());
            ryDepotHead.setProjectStatus(depotHeadItem.getProjectStatus());
            ryDepotHead.setNumber(depotHeadItem.getNumber());
            ryDepotHead.setRemark(depotHeadItem.getRemark());
            ryDepotHead.setFileName(depotHeadItem.getFileName());
            ryDepotHead.setCreateTime(DateUtils.getNowDate());
            ryDepotHead.setCreator(user.getUserId());
            ryDepotHead.setType("其他");
            ryDepotHead.setSubType("项目总清单");
//            ryDepotHead.setCreator(user.getUserId());
            int res2 = ryDepotHeadMapper.insertRyDepotHead(ryDepotHead);

            System.out.println("id---->" + ryDepotHead.getId());
            if(res2 > 0){
                //修改新增的项目总清单记录中的project_head_id为新增的id，供其他业务使用（出入库审核需要使用）
                RyDepotHead updatePara = new RyDepotHead();
                updatePara.setId(ryDepotHead.getId());
                updatePara.setProjectHeadId(ryDepotHead.getId());
                ryDepotHeadMapper.updateRyDepotHead(updatePara);

                //遍历明细数据，新增单据明细数据
                for(RyDepotItem  ryDepotItem : tableData){
                    ryDepotItem.setHeaderId(ryDepotHead.getId());//设置刚生成的主表id
                    //设置入库仓库和出库仓库为刚生成的项目仓库信息
                    ryDepotItem.setDepotId(ryDepot.getId());

                    //如果物品名或物品规格为空则跳过不处理
                    if(StringUtils.isBlank(ryDepotItem.getInventorySpecifications()) || StringUtils.isBlank(ryDepotItem.getInventoryName())){
                        continue;
                    }
                    //判断物品是否存在物品库中
                    RyInventory ryInventory = ryInventoryMapper.selectInfoByNameSpeci(ryDepotItem.getInventorySpecifications().replaceAll(" ","").toUpperCase(), ryDepotItem.getInventoryName().replaceAll(" ","").toUpperCase());
                    if(ryInventory == null){
                        RyInventory ryInventory2 = new RyInventory();
                        // 物品名称
                        ryInventory2.setName(ryDepotItem.getInventoryName().replaceAll(" ",""));
                        // 规格
                        ryInventory2.setSpecifications(ryDepotItem.getInventorySpecifications().replaceAll(" ",""));
                        // wbs编码
                        ryInventory2.setWbs(ryDepotItem.getWbs());
                        // 品牌
                        if (ryDepotItem.getBrand() == null) {
                            ryInventory2.setBrand("/");
                        } else {
                            ryInventory2.setBrand(ryDepotItem.getBrand());
                        }
                        // 供应商ID
                        // ryInventory2.setSupplyId(ryDepotItem.getSupplyId().toString());
                        // 供应商
                        ryInventory2.setSupply(ryDepotItem.getSupply());
                        // 装填
                        ryInventory2.setStatus("0");
                        // 操作员
                        ryInventory2.setOperator(ryDepotItem.getInOperateMan());
                        // 单位
                        ryInventory2.setUnit("");
                        // 单价
                        ryInventory2.setUnitPrice(ryDepotItem.getUnitPrice());
                        // 库位
                        ryInventory2.setLocation(ryDepotItem.getLocation());
                        ryInventoryMapper.insertRyInventory(ryInventory2);
                        ryDepotItem.setInventoryId(ryInventory2.getId());
                    }
                    ryDepotItemMapper.insertRyDepotItem(ryDepotItem);
                }
            }
        }
        return AjaxResult.success("新增成功");
    }

    /**
     * 修改单据主表
     */
    @Override
    @Transactional
    public AjaxResult editDepotHeadAndDetail(DepotHeadItem depotHeadItem){

        System.out.println("depotDetailBean---->" + depotHeadItem);
        //获取用户信息
//        SysUser user = SecurityUtils.getLoginUser().getUser();

        //判断是否有子表数据
        List<RyDepotItem> tableData = depotHeadItem.getTableData();
        if(tableData == null || tableData.size() ==0){
            return AjaxResult.error("子表数据不存在");
        }

        //修改主表数据
        RyDepotHead ryDepotHead = new RyDepotHead();
        ryDepotHead.setId(depotHeadItem.getId());//主键，用于定位修改数据
        ryDepotHead.setProjectCode(depotHeadItem.getProjectCode());
        ryDepotHead.setProjectName(depotHeadItem.getProjectName());
        ryDepotHead.setProjectStatus(depotHeadItem.getProjectStatus());
        ryDepotHead.setNumber(depotHeadItem.getNumber());
        ryDepotHead.setOperTime(DateUtils.getNowDate());
        ryDepotHead.setFileName(depotHeadItem.getFileName());
        ryDepotHead.setUpdateTime(DateUtils.getNowDate());
        ryDepotHead.setRemark(depotHeadItem.getRemark());
        ryDepotHeadMapper.updateRyDepotHead(ryDepotHead);

        //删除单据的明细(原因是修改时也有可能新增明细数据，这些新增明细数据是没有id的)
        ryDepotItemMapper.deleteDepotItemByHeadId(ryDepotHead.getId());

        //遍历明细数据，新增单据明细数据
        for(RyDepotItem ryDepotItem : tableData){
            ryDepotItem.setHeaderId(ryDepotHead.getId());//设置刚生成的主表id

            //如果物品名或物品规格为空则跳过不处理
            if(StringUtils.isBlank(ryDepotItem.getInventorySpecifications()) || StringUtils.isBlank(ryDepotItem.getInventoryName())){
                continue;
            }

            //判断物品是否存在物品库中
            RyInventory ryInventory = ryInventoryMapper.selectInfoByNameSpeci(ryDepotItem.getInventorySpecifications(), ryDepotItem.getInventoryName());
            if(ryInventory == null){
                RyInventory ryInventory2 = new RyInventory();
                // 物品名称
                ryInventory2.setName(ryDepotItem.getInventoryName().replaceAll(" ",""));
                // 规格
                ryInventory2.setSpecifications(ryDepotItem.getInventorySpecifications().replaceAll(" ",""));
                // wbs编码
                ryInventory2.setWbs(ryDepotItem.getWbs());
                // 品牌
                if (ryDepotItem.getBrand() == null) {
                    ryInventory2.setBrand("/");
                } else {
                    ryInventory2.setBrand(ryDepotItem.getBrand());
                }
                // 供应商ID
                // ryInventory2.setSupplyId(ryDepotItem.getSupplyId().toString());
                // 供应商
                ryInventory2.setSupply(ryDepotItem.getSupply());
                // 装填
                ryInventory2.setStatus("0");
                // 操作员
                ryInventory2.setOperator(ryDepotItem.getInOperateMan());
                // 单位
                ryInventory2.setUnit("");
                // 单价
                ryInventory2.setUnitPrice(ryDepotItem.getUnitPrice());
                // 库位
                ryInventory2.setLocation(ryDepotItem.getLocation());
                ryInventoryMapper.insertRyInventory(ryInventory2);
                ryDepotItem.setInventoryId(ryInventory2.getId());
            }

            //设置入库仓库和出库仓库为刚生成的项目仓库信息
            ryDepotItemMapper.insertRyDepotItem(ryDepotItem);
        }

        return AjaxResult.success("修改成功");
    }


    /**
     * 查询单据主表列表
     *
     * @param ryDepotHead 单据主表
     * @return 单据主表
     */
    @Override
    public List<RyDepotHead> selectRyDepotHeadList(RyDepotHead ryDepotHead)
    {
        return ryDepotHeadMapper.selectRyDepotHeadList(ryDepotHead);
    }

    /**
     * 查询可以生成订单的项目明细数据：就是purchase_order_id为空的
     * @param paramBean
     * @return
     */
    public List<RyDepotItem> selectDetailForOrder(ParamBean paramBean){
        if(paramBean.getLinkHeadId() != null){//项目总清单id
            paramBean.setHeaderId(paramBean.getLinkHeadId());
        }
        if(paramBean.getOrganId() != null){//供应商
            //查询供应商信息
            TbCustomers tbCustomers = tbCustomersMapper.selectTbCustomersById(paramBean.getOrganId());
            paramBean.setSupply(tbCustomers.getCompanyName());
        }
        if(paramBean.getBrand() != null){//品牌
            paramBean.setBrand(paramBean.getBrand());
        }
        if(paramBean.getItemName() != null){//物品名
            paramBean.setItemName(paramBean.getItemName());
        }
        List<RyDepotItem> resList = ryDepotItemMapper.selectItemForOrder(paramBean);
        for(RyDepotItem ryDepotItem : resList){
            //根据物品id和总仓库id查询总库库物品当前库存量以及相关信息(总库id为1)
            RyInventoryCurrentStock ryInventoryCurrentStock = new RyInventoryCurrentStock();
            ryInventoryCurrentStock.setInventoryId(ryDepotItem.getInventoryId());//物品id
            ryInventoryCurrentStock.setDepotId(1L);//仓库id
            WareCurrentStock wareCurrentStock = wareCurrentStockMapper.getInfoByDepotInventoryId(ryInventoryCurrentStock);
            if(wareCurrentStock == null){
                ryDepotItem.setUsableNum(Double.valueOf(0));//总库可用数量
            } else {
                ryDepotItem.setUsableNum(wareCurrentStock.getCurrentNumber());//总库可用数量
            }
        }

        return resList;
    }

    /**
     * 根据条件筛选可关联的项目总清单
     * @param list
     * @return
     */
    public List<RyDepotHead> allUsed(List<Long> list){
        return ryDepotHeadMapper.allUsed(list);
    }

    /**
     * 新增单据主表
     *
     * @param ryDepotHead 单据主表
     * @return 结果
     */
    @Override
    public int insertRyDepotHead(RyDepotHead ryDepotHead)
    {
        ryDepotHead.setCreateTime(DateUtils.getNowDate());
        return ryDepotHeadMapper.insertRyDepotHead(ryDepotHead);
    }

    /**
     * 修改单据主表
     *
     * @param ryDepotHead 单据主表
     * @return 结果
     */
    @Override
    public int updateRyDepotHead(RyDepotHead ryDepotHead)
    {
        return ryDepotHeadMapper.updateRyDepotHead(ryDepotHead);
    }

    /**
     * 批量删除单据主表
     *
     * @param ids 需要删除的单据主表主键
     * @return 结果
     */
    @Override
    public int deleteRyDepotHeadByIds(Long[] ids)
    {
        return ryDepotHeadMapper.deleteRyDepotHeadByIds(ids);
    }

    /**
     * 删除单据主表信息
     *
     * @param id 单据主表主键
     * @return 结果
     */
    @Override
    public int deleteRyDepotHeadById(Long id)
    {
        return ryDepotHeadMapper.deleteRyDepotHeadById(id);
    }
}
